home *** CD-ROM | disk | FTP | other *** search
- Path: ccshst05.cs.uoguelph.ca!ccshst01!thay
- From: thay@uoguelph.ca (Toby K Hay)
- Newsgroups: comp.lang.c
- Subject: Re: Counting high bits (was (no subject))
- Date: 29 Feb 1996 23:07:03 GMT
- Organization: University of Guelph
- Message-ID: <4h5bin$i2t@ccshst05.cs.uoguelph.ca>
- References: <4gv493$p09@nuacht.iol.ie>
- NNTP-Posting-Host: ccshst01.cs.uoguelph.ca
- X-Newsreader: TIN [version 1.2 PL2]
-
- Roy Leonard (rleonard@ferrotec.ie) wrote:
- : I have a strange problem from an embedded system. I have an array of
- : data, and
- : I want to count all the high bits (=1) in the array.
- : The data is of fixed length (roughly 50 long ints). Each bit is evenly
- : weighted.
- : Eg.
- : If the data in binary was "1001001", the total I'm looking for is three.
-
- I'm doing this too in a program. My solution was the following routine:
-
- #define INTLENGTH = 16 /* Integer length is 16 bits */
-
- int CountOnes(int SourceInt)
- /* Count the high bits in the integer SourceInt. */
- {
- int i,NumOnes; /* loop index and accumulator */
- NumOnes = 0; /* initialize accumulator */
- for (i=0;i<INTLENGTH;i++) /* for each bit of the integer . . . */
- {
- NumOnes += (1 & SourceInt); /* increment NumOnes if int ends in 1 */
- SourceInt = SourceInt >> 1; /* shift int 1 to the right */
- }
- return NumOnes; /* NumOnes = number of high bits */
- }
-
- I'd be glad to hear from more experienced programmers who know of faster
- ways of doing this.
- Toby Hay thay@uoguelph.ca
-